package com.shi.data_structure.linked_list;

import java.util.Iterator;

public class CircularLinkedListSentinel implements Iterable<Integer>{

    private class Node{
        private Node prev;
        private int value;
        private Node next;

        public Node(Node prev, int value, Node next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    private final Node sentinel = new Node(null, -1, null);

    public CircularLinkedListSentinel() {
        sentinel.next = sentinel;
        sentinel.prev = sentinel;
    }

    @Override
    public Iterator<Integer> iterator(){
        return new Iterator<Integer>() {
            Node p = sentinel.next;
            @Override
            public boolean hasNext() {
                return p != sentinel;
            }

            @Override
            public Integer next() {
                int value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    /**
     * 头插法
     * @param value
     */
    public void addFirst(int value){
        Node next = sentinel.next;
        Node prev = sentinel;
        Node added = new Node(prev, value, next);
        prev.next = added;
        next.prev = added;
    }

    /**
     * 尾插法
     * @param value
     */
    public void addLast(int value){
        Node prev = sentinel.prev;
        Node next = sentinel;
        Node added = new Node(prev, value, next);
        prev.next = added;
        next.prev = added;
    }

    /**
     * 头删法
     */
    public void removeFirst(){
        Node removed = sentinel.next;
        if(removed == sentinel){
            throw new IllegalArgumentException("非法");
        }
        Node prev= sentinel;
        Node next = removed.next;
        prev.next = next;
        next.prev = prev;
    }

    /**
     * 尾删法
     */
    public void removeLast(){
        Node removed = sentinel.prev;
        if(removed == sentinel){
            throw new IllegalArgumentException("非法");
        }
        Node prev = removed.prev;
        Node next = sentinel;
        prev.next = next;
        next.prev = prev;
    }

    /**
     * 根据值删除节点
     * @param value
     */
    public void removeByValue(int value){
        Node removed = findNode(value);
        if (removed != null){
            Node prev = removed.prev;
            Node next = removed.next;
            prev.next = next;
            next.prev = prev;
        }
    }

    /**
     * 根据值查找节点
     * @param value
     * @return
     */
    private Node findNode(int value) {
        Node p = sentinel.next;
        while (p != sentinel){
            if (p.value == value){
                return p;
            }
            p = p.next;
        }
        return null;
    }
}
